#! usr/lib/python
# coding:utf-8
"""
@author: jeffxun
@date  : 2012-06-19
"""
"""
Deal Xml files
"""

import xml.etree.ElementTree as ET

class MXmlFile:
    """
    xml = MXmlFile()\n
    xml.Parse('xmlfiles.xml')\n
    xml.getList()--->return all xmlfiles values\n
    xml.getDictbyAtrrible() -- >return a dict by node's attrible\n
    xml.getDictbyTag() --> return a dict by node's name\n

    the return dict is not right,if the key not all different
    """
    def __init__(self):
        """
        """
        self.__xml    = None
        self.__root   = None
        self._rootchild = []

    def Parse(self,filename):
        """
        """
        try:
            self.__xml = ET.parse(filename)
            self.__root = self.__xml.getroot()
            self._rootchild = self.__root.getchildren()
        except Exception,e:
            print e
            pass

    def getList(self):
        """
        xml.getList()--->return all xmlfiles values\n
        """
        return self.__getList(self.__root)

    def __getList(self,root):
        """
        """
        res = []
        for n in  root.getchildren():
            if not n.getchildren():
                if n.text.strip() == '':
                    res.append(None)
                else:
                    res.append(n.text)
            else :
                res.append(self.__getList(n))
        return res


    def getDictbyAtrrible(self,attrible):
        """
        xml.getDictbyAtrrible() -- >return a dict by node's attrible\n
        the attrible must be different
        """
        return self.__getDictbyAtrrible(attrible,self.__root)


    def __getDictbyAtrrible(self,attrible,root):
        """
        """
        res = {}
        for n in root.getchildren():
            attrib  = n.attrib
            if attrib.has_key(attrible):
                if not n.getchildren():
                    if n.text.strip() == '':
                        res[attrib[attrible]] = None
                    else:
                        res [attrib[attrible]] = n.text
                else :
                    res [attrib[attrible]] = self.__getList(n)
        return res


    def getDictbyTag(self):
        """
        xml.getDictbyTag() --> return a dict by node's name\n
        the node's name must be different
        """
        return self.__getDictbyTag(self.__root)

    def __getDictbyTag(self,root):
        """
        """
        res = {}
        index = 0
        for n in root.getchildren():
            tagtext = n.tag
            if not n.getchildren():
                if n.text.strip() == '':
                    res[tagtext+"_"+str(index)] = None
                else :
                    res[tagtext+"_"+str(index)] = n.text
            else :
                res[tagtext+"_"+str(index)] = self.__getDictbyTag(n)
            index += 1
        return res
    def GetXmlList(self,mainkey,keylist=[],childkey=[]):
        """ """
        result = {}
        for item in self._rootchild:
            tmpList = []
            for key in keylist:
                valuelist =  item.findall(key)
                if len(valuelist) <=0:
                    continue
                elif len(valuelist) == 1:
                    tmpList.append(valuelist[0].text.encode('utf-8'))
                else:
                    for val in valuelist:
                        ctmpList = []
                        for ckey in childkey:
                            cvaluelist = val.findall(ckey)
                            if len(cvaluelist) <=0:
                                continue
                            elif len(cvaluelist) == 1:
                                ctmpList.append(cvaluelist[0].text.encode('utf-8'))
                            else:
                                print valuelist
                        tmpList.append(ctmpList)
            keyvalue = item.findall(mainkey)
            result[keyvalue[0].text.encode('utf-8')] = tmpList
       # print result['0']
        return result
    def GetXmlListEx(self,mainkey,keylist=[]):
        """ """
        result = {}
        for item in self._rootchild:
            tmpList = []
            for key in keylist:
                valuelist =  item.findall(key)
                tmpList.extend(self._readChild(valuelist))
            keyvalue = item.findall(mainkey)
            result[keyvalue[0].text.encode('utf-8')] = tmpList
        return result
        
    def _readChild(self,valueList):
        """ """
        #print valueList
        res = []
        for val in valueList:
            child =  val.getchildren()
            if child:
                res.append(self._readChild(child))
                #print child
                #print self._readChild(child)
            else:
                #item = {}
                #item[val.tag] = val.text
                item = val.text.encode('utf-8')
                res.append(item)
        return res
        
    def GetXmlDict(self,mainkey,keylist=[],childkey=[]):
        """
        # 读取xml文件内容
        # @mainkey : 返回时数据以字典形式返回，提供的主关键字
        # @keylist : 需要返回数据列表的tagname
        # @childkey : 如果keylist中有多个重复的，指定重复列表中需要返回的数据关键字，首字段为key，其他为value
        """
        result = {}
        #ctmpDict = {}
        for item in self._rootchild:
            tmpList = []
            for key in keylist:
                valuelist =  item.findall(key)
                if len(valuelist) <=0:
                    continue
                elif len(valuelist) == 1:
                    tmpList.append(valuelist[0].text.encode('utf-8'))
                else:
                    ctmpDict = {}
                    for val in valuelist:
                        ctmpList= []
                        for clist in childkey[1:]:
                            cvaluelist = val.findall(clist)
                            if len(cvaluelist) <=0:
                                continue
                            elif len(cvaluelist) == 1:
                                ctmpList.append(cvaluelist[0].text.encode('utf-8'))
                            else:
                                print valuelist
                        ckey = val.findall(childkey[0])
                        ctmpDict[ckey[0].text.encode('utf-8')] = ctmpList
                    tmpList.append(ctmpDict)
            keyvalue = item.findall(mainkey)
            result[keyvalue[0].text.encode('utf-8')] = tmpList
        return result
if __name__ == "__main__":
    print help(MXmlFile)
    #xml = MXmlFile()
    #xml.Parse("../other/general_condition.xml")
    #xml.SetNodes("server","111")
    #print xml.GetXmlList("nID",["nForce","nWit","nPower","nCommand","nForceAdd","nWitAdd","nPowerAdd","nCommAdd"])
#===============================================================================
#test("config\msg.xml")
#test("server.xml")

#xml = MXmlFile()
#xml.Parse("server.xml")
#xml.SetNodes("server","111")
#xml.Parse("config\msg.xml")
#print xml.getList()

###print xml.getDictbyTag()
#print xml.getDictbyAtrrible("id")
